<?php
/**
 * 用户登录
 */
require_once dirname(__DIR__) . "/common.php";
use app\cls\tom\Response;
use app\cls\tom\Tools;

if(empty($_REQUEST["code"]) || empty($_REQUEST["raw_user_data"])  || empty($_REQUEST["wx_sign"]) ){
    Response::output(-1,"参数错误");
}
$code = $_REQUEST["code"];//授权码
$rawUserData = $_REQUEST["raw_user_data"];//用于校验签名数据
$wxSign = $_REQUEST["wx_sign"];//微信加密串
$weixin_name=$_REQUEST['nickName'];//微信呢称
$weixin_pic=$_REQUEST['avatarUrl'];//微信头像
$rawUserDataArr = @json_decode($rawUserData,true);
//判断数据中是否有呢称和头像
if(empty($rawUserDataArr["nickName"]) || empty($rawUserDataArr["avatarUrl"])){
    $name_suffix_key1=rand();
    $name_suffix_key2=rand(1,1000);
    $rawUserDataArr["nickName"]="逗牛短视频1".$name_suffix_key1.$name_suffix_key2;
    if(empty($weixin_pic)){
        $rawUserDataArr["avatarUrl"]="https://s-js.sports.cctv.com/host/resource/future/3mrtx.png";
    }else{
        $rawUserDataArr["avatarUrl"]=$weixin_pic;
    }
}
if(empty($rawUserDataArr["nickName"]) || empty($rawUserDataArr["avatarUrl"])){
    Response::output(-1,"数据格式错误");
}

try {
    //微信的这个
    $appKey = WX_PUBLIC_APP_ID;
    $appSecret = WX_PUBLIC_APP_SECRECT;
    $result = Tools::curl("https://api.weixin.qq.com/sns/jscode2session", [
        "appid" => $appKey, "secret" => $appSecret,
        "js_code" => $code, "grant_type" => "authorization_code"]);
    $res = @json_decode($result,true);
//    var_dump($res);exit;
    if(!isset($res["openid"])){
//        Response::output(-1,"服务器异常 msg==>".$res["errcode"].":".$res["errmsg"]);
        $re123=$res["errcode"]."--".$_SERVER['REMOTE_ADDR'];
        Response::output(-1,"服务器异常 msg==>".$re123.":".$res["errmsg"]);
    }
    //写日志
    Tools::writeLog(["detail"=>$res,"key"=>"login"]);
    $sessionKey = $res["session_key"];
    //数据签名校验
    if(sha1($rawUserData.$sessionKey) != $wxSign){
        Response::output(-1,"数据可能已经被串改");
    }
    $userInfo = json_decode($rawUserData,true);
    $userInfo["open_id"] = $res["openid"];
    $userService = new \app\service\User();
    $re = $userService->login($userInfo);
    Response::outputSelf($re);
} catch (Exception $e) {
//    Response::output(-1,"登录失败 msg==>".$e->getMessage());
    Response::output(-1,"登录失败 msg==>".$_SERVER['REMOTE_ADDR'].$e->getMessage());
}


